package mx.netbrain.converter;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

import mx.netbrain.dao.GroupDao;
import mx.netbrain.dao.impl.GroupDaoImpl;
import mx.netbrain.model.Groups;

public class GroupConverter implements Converter {

	public static List<Groups> groupsBD;

	static {
		GroupDao groupDao = new GroupDaoImpl();
		groupsBD = new ArrayList<Groups>();
		groupsBD = groupDao.listAll();
	}

	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String submittedValue) {
		if(submittedValue.trim().equals("")){
			return null;
		} else {
			try{
				Long number = Long.parseLong(submittedValue);
				for(Groups g : groupsBD){
					if(number.equals(g.getId())){
						return g;
					}
				}
			}catch(NumberFormatException exception){
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Error de conversion",
						"Numero no valido"));
			}
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) {
		if(value == null || value.equals("")){
			return "";
		} else {
			return String.valueOf(((Groups) value).getId());
		}
	}
}
